package classLoading.classLoader;

import sun.misc.Launcher;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 验证类加载机制
 */
public class ClassLoaderDemo {
    static Class helloService;
    public static void main(String[] args) throws Exception {
        String path = "file:/Users/guopanbo/Documents/study/java/test/";
        ClassLoader loader = new URLClassLoader(new URL[]{new URL(path)});
        while(true) {
            if (loader == null)
                break;
            Class<?> aClass = loader.loadClass("HelloService");
            System.out.println("加载HelloService， 类加载器：" + aClass.getClassLoader());
            Object o = aClass.newInstance();
            Method test = aClass.getDeclaredMethod("test");
            test.invoke(o);
            // 用静态变量来存储这个类的class对象
            helloService = aClass;

            // 让classLoader被回收
            loader = null;
            // 让对象被回收
            o = null;

            Thread.sleep(3000);
            System.gc();
        }
        Thread.sleep(5000);
        // 调用gc
        System.gc();
    }
}
